package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jdk.nashorn.internal.runtime.UnwarrantedOptimismException;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {


    @Autowired
    private RestHighLevelClient client;

    @Override
    public void listenHotelInsertOrUpdate(Long id) {
        try {

            Hotel hotel = getById(id);
            HotelDoc hotelDoc = new HotelDoc(hotel);
            IndexRequest indexRequest =
                    new IndexRequest("hotel").id(hotel.getId().toString());
            indexRequest.source(JSON.toJSONString(hotelDoc), XContentType.JSON);

            client.index(indexRequest, RequestOptions.DEFAULT);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void listenHotelDelete(Long id) {

        try {
            DeleteRequest deleteRequest = new DeleteRequest("hotel",id.toString());
            client.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 酒店查询   关键字查询  分页
     *
     * @param param
     * @return
     */
    @Override
    public PageResult search(RequestParams param) {
        try {
            //1.请求对象
            SearchRequest request = new SearchRequest("hotel");
            //2.准备DSl语句
            //条件查询
            buildBasicQuery(param, request);

            //分页
            Integer page = param.getPage();
            Integer size = param.getSize();
            request.source().from((page - 1) * size).size(size);

            //价格升序
            if (param.getSortBy() != null
                    && !"".equals(param.getSortBy())
                    && "price".equals(param.getSortBy())) {
                request.source().sort(param.getSortBy(), SortOrder.ASC);
            }
            //评分降序
            if (param.getSortBy() != null
                    && !"".equals(param.getSortBy())
                    && "score".equals(param.getSortBy())) {
                request.source().sort(param.getSortBy(), SortOrder.DESC);
            }
            //排序   按照距离查询
            if (param.getLocation() != null && !"".equals(param.getLocation())) {
                request.source().sort(SortBuilders.geoDistanceSort("location",
                                new GeoPoint(param.getLocation()))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS));
            }

            //高亮
            if (param.getKey() != null && !"".equals(param.getKey())) {
                request.source().highlighter(new HighlightBuilder()
                        .field("name")
                        .preTags("<em>")
                        .postTags("</em>")
                        .requireFieldMatch(false));
            }

            //3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //4.解析结果
            return handleResponse(param, response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 聚合查询
     */
    @Override
    public Map<String, List<String>> getFilters(RequestParams param) {

        try {
            // 1.准备Request
            SearchRequest searchRequest = new SearchRequest("hotel");
            // 2.准备DSL
            // 2.1.query
            buildBasicQuery(param, searchRequest);
            // 2.2.设置size
            searchRequest.source().size(0);
            // 2.3.聚合
            extracted(searchRequest);
            // 3.发出请求
            SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
            // 4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = search.getAggregations();
            // 4.1.根据品牌名称，获取品牌结果
            List<String> brandAgg = getAggByName(aggregations, "brandAgg");
            result.put("brand", brandAgg);
            List<String> cityAgg = getAggByName(aggregations, "cityAgg");
            result.put("city", cityAgg);
            List<String> starAgg = getAggByName(aggregations, "starAgg");
            result.put("starName", starAgg);
            return result;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 自动补全
     */
    @Override
    public List<String> getSuggestions(String prefix) {
        try {
            SearchRequest searchRequest = new SearchRequest("hotel");
            //构建dsl
            searchRequest.source().suggest(new SuggestBuilder()
                    .addSuggestion("suggestions", SuggestBuilders
                            .completionSuggestion("suggestion")
                            .size(10)
                            .prefix(prefix)
                            .skipDuplicates(true)));
            //发起请求
            SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
            // 解析结果
            Suggest suggest = search.getSuggest();
            CompletionSuggestion completionSuggestion = suggest.getSuggestion("suggestions");
            List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getOptions();
            List<String> collect = options.stream().map(item -> item.getText().toString()).collect(Collectors.toList());

            return collect;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        //根据聚合名称获取局和结果
        Terms terms = aggregations.get(aggName);
        //获取buckets
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        List<String> list = buckets.stream().map(item -> item.getKeyAsString()).collect(Collectors.toList());
        return list;
    }

    private void extracted(SearchRequest searchRequest) {
        searchRequest.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100));
        searchRequest.source().aggregation(AggregationBuilders
                .terms("cityAgg")
                .field("city")
                .size(100));
        searchRequest.source().aggregation(AggregationBuilders
                .terms("starAgg")
                .field("starName")
                .size(100));
    }

    private void buildBasicQuery(RequestParams param, SearchRequest request) {
        //布尔查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字查询
        if (param.getKey() != null && !param.getKey().equals("")) {
            boolQuery.must(QueryBuilders.matchQuery("all", param.getKey()));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        //城市精确查询
        if (param.getCity() != null && !param.getCity().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("city", param.getCity()));
        }

        //品牌精确查询
        if (param.getBrand() != null && !param.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand", param.getBrand()));
        }

        //星级精确查询
        if (param.getStarName() != null && !param.getStarName().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("starName", param.getStarName()));
        }

        //价格范围查询
        if (param.getMinPrice() != null && param.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(param.getMinPrice()).lte(param.getMaxPrice()));
        }

        //广告置顶，重新算分   isAD=true的加分
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                //原始查询条件
                boolQuery,
                // function score  数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //过滤条件
                                QueryBuilders.termQuery("isAD", true),
                                //算分函数
                                ScoreFunctionBuilders.weightFactorFunction(5)
                        )
                }
        );
        request.source().query(functionScoreQuery);
    }

    private PageResult handleResponse(RequestParams param, SearchResponse response) {
        SearchHits searchHits = response.getHits();
        //获取总条数
        long total = searchHits.getTotalHits().value;
        System.out.println("总条数：" + total);
        //获取文档数组
        SearchHit[] hits = searchHits.getHits();
        List<HotelDoc> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            System.out.println(hit.toString());
            String sourceAsString = hit.getSourceAsString();
            //对象转换
            HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
            //获取距离数值
            Object[] sortValues = hit.getSortValues();

            if (param.getLocation() != null) {
                if (sortValues.length > 0) {
                    Object distance = sortValues[1];
                    hotelDoc.setDistance(distance);
                }
            }
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields.size() > 0) {
                HighlightField name = highlightFields.get("name");
                String s = name.getFragments()[0].toString();
                hotelDoc.setName(s);
            }
            list.add(hotelDoc);
        }
        return new PageResult(total, list);
    }
}
